package com.NULL.phony.filter;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.util.Linkify;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MessageActivity extends Activity {
	public static final String ACTION = "com.NULL.phony.filter.VIEW";
	private static final int CHECK_INDEX = 0;
	private long latest = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		onNewIntent(this.getIntent());

		testMessageList();

		OneRingCall.start(this);
	}

	private void testMessageList() {
		this.showABlockedSms(new Date().getTime(), "138012345678",
				this.getString(R.string.TestMessage));
		this.showABlockedSms(new Date().getTime()+100000, "138012345678",
				this.getString(R.string.TestMessage));
	}

	@Override
	protected void onNewIntent(Intent intent) {
		DB db = new DB(this);
		Cursor cursor = db.query(latest);
		while (cursor.moveToNext()) {
			showABlockedSms(db.getAcceptedTime(cursor), db.getPhone(cursor),
					db.getMessage(cursor));
		}
		cursor.close();
		db.close();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.About:
			about(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	private void showABlockedSms(long acceptedTime, String phone, String message) {
		LinearLayout smsTable = (LinearLayout) this.findViewById(R.id.smsTable);
		LinearLayout smsUI = new LinearLayout(this);
		smsTable.addView(smsUI,0);
		this.setID(smsUI, acceptedTime);

		CheckBox checkUI = new CheckBox(this);
		smsUI.addView(checkUI);
		LinearLayout.LayoutParams checkLayout = (LinearLayout.LayoutParams) checkUI
				.getLayoutParams();
		checkLayout.topMargin = 10;
		checkUI.requestLayout();

		TextView msgUI = new TextView(this);
		smsUI.addView(msgUI);
		msgUI.setText(phone + " @ " + smartWhen(acceptedTime) + "\n\r"
				+ message);
		Linkify.addLinks(msgUI, Linkify.ALL);
		LinearLayout.LayoutParams msgLayout = (LinearLayout.LayoutParams) msgUI
				.getLayoutParams();

		msgLayout.weight = 1f;
		msgUI.requestLayout();
		msgUI.setAutoLinkMask(Linkify.ALL);
		smsUI.requestLayout();
		latest = acceptedTime;
	}

	public void onDelete(View btnDelete) {
		DB db = new DB(this);
		LinearLayout smsTable = (LinearLayout) this.findViewById(R.id.smsTable);
		LinearLayout smsUI;
		CheckBox checkUI;
		for (int i = smsTable.getChildCount() - 1; i > -1; i--) {
			smsUI = (LinearLayout) smsTable.getChildAt(i);
			checkUI = (CheckBox) smsUI.getChildAt(CHECK_INDEX);
			if (!checkUI.isChecked())
				continue;
			db.remove(this.getID(smsUI));
			smsTable.removeView(smsUI);
		}
		db.close();
	}

	public void onCheckAll(View view) {
		boolean checked = ((CheckBox) view).isChecked();
		LinearLayout smsTable = (LinearLayout) this.findViewById(R.id.smsTable);
		LinearLayout smsUI;
		CheckBox checkUI;
		for (int i = smsTable.getChildCount() - 1; i > -1; i--) {
			smsUI = (LinearLayout) smsTable.getChildAt(i);
			checkUI = (CheckBox) smsUI.getChildAt(CHECK_INDEX);
			checkUI.setChecked(checked);
		}
	}

	private void setID(View row, long ID) {
		row.setTag(new Long(ID));
	}

	private long getID(View row) {
		return (Long) row.getTag();
	}

	private String smartWhen(long whenMillis) {
		SimpleDateFormat formatPattern = new SimpleDateFormat("yyMMdd");
		Date when = new Date(whenMillis);
		Date now = new Date();
		int days = Integer.parseInt(formatPattern.format(now))
				- Integer.parseInt(formatPattern.format(when));
		if (days == 0)
			formatPattern.applyPattern("HH:mm");
		else if (days == 1)
			formatPattern.applyPattern("'" + this.getString(R.string.Yesterday)
					+ "' HH:mm");
		else
			formatPattern.applyPattern("yyyy-MM-dd HH:mm");

		return formatPattern.format(when);
	}

	private void about(Context context) {
		// Try to load the a package matching the name of our own package
		PackageInfo pInfo;
		String versionInfo;
		try {
			pInfo = context.getPackageManager().getPackageInfo(
					context.getPackageName(), PackageManager.GET_META_DATA);
			versionInfo = pInfo.versionName;
		} catch (NameNotFoundException e) {
			versionInfo = "Not Known";
		}

		String aboutTitle = String.format("About %s",
				context.getString(R.string.app_name));
		String versionString = String.format("Version: %s", versionInfo);
		String aboutText = context.getString(R.string.Copyright);

		// Set up the TextView
		final TextView message = new TextView(context);
		// We'll use a spannablestring to be able to make links clickable
		final SpannableString s = new SpannableString(aboutText);

		// Set some padding
		message.setPadding(5, 5, 5, 5);
		// Set up the final string
		message.setText(versionString + "\n\n" + s);
		// Now linkify the text
		Linkify.addLinks(message, Linkify.ALL);

		new AlertDialog.Builder(context)
				.setTitle(aboutTitle)
				.setCancelable(true)
				.setIcon(R.drawable.icon)
				.setPositiveButton(context.getString(android.R.string.ok), null)
				.setView(message).create().show();
	}

}